package com.xjscrm.console.service.customer.childUser.impl;

import com.xjscrm.common.constant.CacheKey;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.MerchatChild;
import com.xjscrm.common.entity.MerchatChildDevceRelation;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.console.mapper.MerchatChildDevceRelationMapper;
import com.xjscrm.console.mapper.MerchatChildMapper;
import com.xjscrm.console.param.user.BatchDeleStaffDto;
import com.xjscrm.console.param.user.MerchatChildDevceRelationQuery;
import com.xjscrm.console.service.customer.childUser.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StaffServiceImpl implements StaffService {

    @Autowired
    private MerchatChildMapper merchatChildMapper;

    @Autowired
    private MerchatChildDevceRelationMapper merchatChildDevceRelationMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleStaffBySelect(BatchDeleStaffDto batchDeleStaffDto) {
        MerchatChild merchatChild = merchatChildMapper.getById(batchDeleStaffDto.getId(), batchDeleStaffDto.getMerId());
        if(merchatChild==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.USER_UNREG);
        }
        //删除员工
        int i = merchatChildMapper.deleMerchatChildById(merchatChild.getId(), merchatChild.getMerId());
        if(i==0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.NET_ERROR);
        }
        //删除员工与机器人关系
        MerchatChildDevceRelationQuery merchatChildDevceRelationQuery=new MerchatChildDevceRelationQuery();
        merchatChildDevceRelationQuery.setMerId(merchatChild.getMerId());
        merchatChildDevceRelationQuery.setChildMerchatId(merchatChild.getId());
        List<MerchatChildDevceRelation> merchatChildDevceRelationList = merchatChildDevceRelationMapper.getmerchatChildDevceRelation(merchatChildDevceRelationQuery);
        if(merchatChildDevceRelationList!=null&&!merchatChildDevceRelationList.isEmpty()){
            for (MerchatChildDevceRelation merchatChildDevceRelation:merchatChildDevceRelationList) {
                merchatChildDevceRelationMapper.deleById(merchatChildDevceRelation.getId(), merchatChildDevceRelationQuery.getMerId());
            }
        }

        //删除redis中 主账号和子账号的关系
        redisTemplate.delete(String.format(CacheKey.MERCHAT_CHILEMERCHST_RELATION,merchatChild.getUserAccount()));
        // 删除聊天会话数数量限制缓存
        redisTemplate.delete(String.format(CacheKey.SYNC_CUSTOMER_TAG_CACHE, merchatChild.getId()));
    }
}
